<template>
	<view class="root">
		<view class="item-container" v-if="loading">
			<!-- 标题显示 -->
			<text class="item-title">{{blog.title}}</text>
			<!-- 文章内容显示 -->
			<text class="item-author">{{blog.user.nickName}}@{{blog.createTime}}</text>
			<rich-text :nodes="blog.content" class="item-desc"></rich-text>
			<!-- 图片显示 -->
			<image :src="blog.picture" mode="widthFix" class="item-focus"></image>
			<!-- 头像显示 -->
			<image :src="blog.user.avatar" mode="aspectFill" class="item-avatar"></image>
			<!-- 显示标签，标签就是文本 -->

			<view class="icon-container">
				<!-- <image src="/static/icons(1)/ic_good.png" class="icon"></image> -->
				<text
					:class="goodIds.indexOf(blog.id)>=0?'iconfont icon-xihuan1 ic-red':'iconfont icon-xihuan1 ic-gray' "
					@click.stop="changeGood(blog.id)"></text>
				<text class="icon-text">{{blog.good}}</text>
				<image src="/static/icons(1)/ic_comment.png" class="icon"></image>
				<text class="icon-text">{{blog.comments.length}}</text>
				<image src="/static/icons(1)/ic_count.png" class="icon"></image>
				<text class="icon-text">{{blog.readCount}}</text>
			</view>
			<!-- <image src="/static/icons(1)/ic_delete.png" class="icon-tag"></image> -->
			<text class="iconfont icon-tianranqi icon-tag" @click.stop="drop(item.id)"></text>
		</view>
		
		<view v-if="hasComment" class="item-container">
			<view v-for="(parent,index) in parents" :key="parent.id">
				<view class="cmt-container">
					<text class="cmt-author">{{parent.nickName}}</text>
					<text class="cmt-time">{{parent.createTime}}</text>
					<image :src="parent.avatar" mode="aspectFill" class="cmt-avatar"></image>
					<text class="cmt-content" @click="clickReply(parent)">{{parent.content}}</text>
				</view>
				<!-- 子评论列表 -->
				<view v-if="replies[index].length>0" class="reply-container">
				   <view v-for="(reply,idx) in replies[index]" class="reply-item" :key="reply.id">
					   <view class="reply-info">
						   <text class="reply-author">{{reply.nickName}}</text>
						   <text class="reply-to">@{{reply.toUser}}</text>
						   <text class="reply-time">{{reply.createTime}}</text>
					   </view>
					   <view class="reply-content" @click="clickReply(reply)">{{reply.content}}</view> 
				   </view>
				</view>
				<view v-if="index <parents.length -1" class="cmt-line"></view><!-- 分割线 -->
			</view>
		</view>
		
		<view class="input-container">
			<image :src="avatar" mode="aspectFill" class="input-avatar" @click="showuser"></image>
			<textarea auto-height :value="inputValue" @input="inputGetArea" :placeholder="inputHolder" class="input-area" placeholder-class="input-holder"/>
			<text class="iconfont icon-jinru input-commit" @click="clickCommit"></text>
			<view class="">
				<login-dialog ref="login" @login="afterLogin"></login-dialog>
			</view>
		</view>
	</view>
</template>

<script>
	import LoginDialog from '@/components/dialog-shell/login-dialog.vue'

	export default {
		components: {
			LoginDialog
		},
		data() {
			return {
				goodIds: [],
				blog: {},
				loading: false,
				parents:[],
				replies:[],
				hasComment:false,
				avatar:'../../static/icons(1)/default_user.png',
				inputValue:'',
				inputHolder:'请输入评论内容...',
				parentId:null,
				app: null
			};
		},
		created() {
			this.app = getApp()
		},
		onLoad(options) {
			let id = options.id;
			this.getBlog(id);
		},
		methods: {
			clickCommit(){
				if(this.app.globalData.token.length === 0){
					this.$refs.login.show();
					return;
				}
				if(this.inputValue.length === 0){
					uni.showToast({ 
						title: '请输入评论内容',
						icon: 'fail'
					});
					return;
				}
				const url = this.$params.host + this.$params.action_comment;
				const data = {
					nick_name: this.app.globalData.nickName,
					avatar: '/'+this.app.globalData.avatar,
					email: this.app.globalData.email,
					content: this.inputValue,
					blog_id: this.blog.id,
					parent_id: this.parentId,
					token: this.app.globalData.token,
					is_owner: this.app.globalData.id == this.blog.user.id
				};
				uni.showLoading({ title: '上传评论', mask: false });
				this.$req.post(url, data, res => {
					res = res.data;
					const cmt = res.data;
					let comments=this.blog.comments.concat(cmt)
					this.blog.comments=comments
					this.formatComments(comments)
					this.hasComment=this.blog.comments.length>0
					this.inputValue=''
					this.parentId=null
					this.inputHolder='请输入评论内容'
					uni.hideLoading();
				}, () => {
					uni.hideLoading();
				});
			},
			clickReply(reply){
				this.parentId = reply.id;
				this.inputHolder = '@'+reply.nickName; 
			},
			inputGetArea(e){
				this.inputValue = e.detail.value
			},
			afterLogin(){
				this.avatar = this.$params.host + this.app.globalData.avatar;
			},
			showuser(){
				this.$refs.login.show();
			},
			getBlog(id) {
				let url = this.$params.host + this.$params.action_top_blogs + id;
				this.$req.get(url, (res) => {
					let blog = res.data.data;
					uni.setNavigationBarTitle({
						title: blog.user.nickName
					})
					blog.picture = this.$params.host + blog.picture;
					blog.user.avatar = this.$params.host + blog.user.avatar;
					blog.createTime = this.$formatTime(new Date(blog.createTime));
					blog.updateTime = this.$formatTime(new Date(blog.updateTime));
					blog.content = blog.content.replace(/https/gi, 'http').replace(/\<img/gi,
						'<img class="rich-img"')
					this.blog = blog
					this.formatComments(blog.comments)
					this.loading = true
					this.addReadCount(id)
				});
			},
			addReadCount(id) {
				let url = this.$params.host + this.$params.action_read_count
				let data = {
					id: id
				}
				this.$req.postQuery(url, data, res => {
					// console.log(res);
					this.blog.readCount = res.data.data
					//第一种获取页面栈实例的方法
					// this.refreshPrevPage(id,res.data.data)
					//第二种：通知中心
					let count = res.data.data
					this.$noti.post(this.$params.noti_refresh_count, {
						id,
						count
					})
				}, () => {
					// this.getBlog(id)
				})
			},
			refreshPrevPage(id, count) {
				let pages = getCurrentPages()
				let prev = pages[pages.length - 2]
				prev.refreshReadCount(id, count)
			},
			changeGood(id) {
				let good = true //代表当前是点赞还是取消点赞
				if (this.goodIds.indexOf(id) >= 0) {
					good = false
				}
				if (good) {
					//1.把当前blog的id保存到缓存 2.把点赞加1发送到服务器
					this.goodIds = [...this.goodIds, id]
				} else {
					//1.把当前blog的id从缓存集合中删除 2.把点赞加1发送到服务器
					let index = this.goodIds.indexOf(id)
					if (index >= 0) {
						//删除方法
						//1.this.goodIds=this.goodIds.splice(index,1) splice靠循环来遍历事件
						//2.this.goodIds.shift() shift删除最后一个元素
						//3.this.goodIds.pop() pop删除最后一个元素
						this.goodIds[index] = this.goodIds[this.goodIds.length - 1]
						this.goodIds.pop()
					}
				}
				uni.setStorageSync(this.$params.key_good_ids, this.goodIds)
				this.postGood(id, good)
			},
			postGood(id, good) {
				uni.showLoading({
					title: '点赞...',
					mask: false
				});
				let url = this.$params.host
				let action = good ? this.$params.action_good : this.$params.action_del_good
				url += action
				let data = {
					"id": id
				}
				this.$req.postQuery(url, data, res => {
					this.blog.good=res.data.data
					this.$noti.post(this.$params.noti_change_good,{
						id:id,
						count:res.data.data
					})
				}, () => {
					uni.hideLoading()
				})
			},
			formatComments(comments){
				if(comments.length==0){
					return 
				}
				let parents=[]
				comments.forEach(c=>{
					if (!c.avatar?.startsWith('http')) { 
						c.avatar = this.$params.host + (c.avatar?.startsWith('/') ? c.avatar : `/${c.avatar}`); 
					}
					c.createTime=this.$formatTime(new Date(c.createTime))
					if(c.parentId==null){
						parents.push(c)
					}
				})
				parents.sort(function(p1,p2){
					return new Date(p2.createTime).getTime() - new Date(p1.createTime).getTime()
				})
				let replies = Array.from({length: parents.length}, () => [])
				let index = 0
				parents.forEach(p => {
					let cmmts=[]
				    cmmts = [...cmmts,...this.findAllChildren(p,comments)]
						replies[index++] = cmmts
				})
				console.log(replies);
				this.parents=parents
				this.replies=replies
				this.hasComment=comments.length>0
			},
				findAllChildren(parent,comments){
					let result=[]
					comments.forEach(c =>{
						if(c.parentId == parent.id){
							c.toUser = parent.nickName
							result.push(c)
							result = [...result,...this.findAllChildren(c,comments)]
						}
					})
					return result
				}
		}
	};
</script>

<style>
	@import url("blog.css");
</style>